package awk.disruptor;

import com.lmax.disruptor.EventTranslatorOneArg;
import com.lmax.disruptor.RingBuffer;

/**
 * @description:
 * @author: wanghaifeng
 * @date: 2020/12/23 生产者，在此类中向disruptor发布消息
 */
public class MessageEventProducer {

	private RingBuffer<MessageEvent> ringBuffer;

	public MessageEventProducer(RingBuffer<MessageEvent> ringBuffer) {
		this.ringBuffer = ringBuffer;
	}

	/**
	 * 将接收到的消息输出到ringBuffer
	 */
	public void onData(String message) {
		//请求下一个事件序号；
		long sequence = ringBuffer.next();
		//获取该序号对应的事件对象；
		MessageEvent event = ringBuffer.get(sequence);
		event.setMessage(message);
		System.out.println("生产者发布消息:" + message);
		ringBuffer.publish(sequence);
		//也可以这样
//        EventTranslatorOneArg<MessageEvent, String> translator = (messageEvent, l, o2) -> messageEvent.setMessage(o2);
//        ringBuffer.publishEvent(translator, message);

	}
}
